"use strict";

//todo
var dappAddress = "n1zWNyQ7qzeV58DtA35aboBc8iKoQXDG3uH";
var hash = "a995835fd64824974b53e3b511d259f912c0072ea3456cec64ee08af26dc2f26";
var NebPay = require("nebpay");
var nebPay = new NebPay();
var html = '';
var userInfo = '';
var address = '';

function init(){
  getUserInfo();
  getUser();
  getList();
}

init();

function getUserInfo(index){
  nebPay.simulateCall(dappAddress, "0", "getUserInfo", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          layer.msg('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      userInfo = JSON.parse(res.result);
      var userInfo2 = JSON.parse(res.result);
      console.log('getUserInfo',res)
      console.log('getUserInfo',userInfo,userInfo.TipsCoin,TipsCoin['TipsCoin'],userInfo2.TipsCoin,userInfo2)
      if(userInfo){
        $('#coin').html(userInfo.TipsCoin);
        index && layer.close(index);
      }else{
        index && layer.msg('出现错误，请刷新后重试')
      }
    }
  })
}

function getUser(){
  nebPay.simulateCall(dappAddress, "0", "getUser", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          layer.msg('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      console.log('getUser',res,console.log(res.result))
      address = JSON.parse(res.result);
      if(!userInfo){
        noUserInfo(address);     
      }
    }
  })
}

function getList(){
  nebPay.simulateCall(dappAddress, "0", "get", JSON.stringify([]), {
      listener: function(res) {
        if(res.result == '' && res.execute_err == 'contract check failed') {
            layer.msg('合约检测失败，请检查浏览器钱包插件环境！');
            return;
        }
        var datalist = JSON.parse(res.result);
        console.log('getList',datalist);
        renderSearch(datalist)
      }
  })
}

function noUserInfo(address){
  layer.msg('您好，初次使用自动注册中，注册成功将免费赠送给您100TCoin', {
    icon: 6,
    time: 5000,
    shade: 0.7
  });
  getCoin(address);
}

function getCoin(address){
  console.log('getCoin address',JSON.stringify([address]),address)
  nebPay.call(dappAddress, "0", "getCoin", JSON.stringify([]), { 
    listener: function(res) {
      console.log('getCoin',res)
      if (res.txhash) {
        var index = layer.msg('已提交，等待确认',{time: 5 * 60 * 1000,icon: 1,shade: 0.7});
        var timer = setInterval(() => verificatHash(res.txhash, index, timer), 3000);
      }else{
        layer.msg('出现错误，请检查浏览器钱包插件环境，刷新后再试');
      }
    }
  })
}

function verificatHash(txhash, index, timer){
  var data = {
    'hash':txhash
  }
  //todo
  $.post("https://testnet.nebulas.io/v1/user/getTransactionReceipt",JSON.stringify(data),function(res){
    console.log('verificatHash',res,res.result)
    if(res.result.status === 1){
      clearInterval(timer);
      getUserInfo(index);
    }
  });
}

function useCoin(useInfo){
  if(!userInfo){
    noUserInfo(address);     
  }else{
    nebPay.call(dappAddress, "0", "useCoin", JSON.stringify([userInfo]), { 
      listener: function(res) {
        if (res.txhash) {
          layer.msg('信息存入需要30s，之后可刷新网页，查看排行榜',{
            time: 5000
          });
        }
      }
    })
  }
}

function renderSearch (data) {
  var datas = JSON.parse(data);
  console.log(datas);

  if (datas && datas.length) {
    var datalist = datas.sort(function (a, b) {
      var value1 = a.active,
          value2 = b.active;
      if(value1 === value2){
          return a.step - b.step;
      }
      return value2 - value1;
    })
    
    for (var i = 0; i < datalist.length; i++) {
      if (i < 20) {
        html += `<tr><td>${i+1}</td><td>${datalist[i].username}</td><td>${datalist[i].active}</td><td>${datalist[i].step}</td></tr>`
      }
    }
  } else {
    html += '<tr><td>暂无数据！</td></tr>'
  }
}


$('#ranking').click(function(){
  if(html){
    layer.open({
      type: 1,
      title: '排行榜前20',
      skin: 'layui-layer-rim',
      area: ['420px', '240px'], //宽高
      content: `<div id='rankList'><table><tr><th>名次</th><th>用户名</th><th>已闯关</th><th>已走步数</th></tr>${html}</table></div>`
    });
  }else{
    layer.msg('正在加载中，请稍后再试');
  }
})

$('#upload').click(function(){
  layer.prompt(function(val){
    var usernameV = val;
    var activeV = window.active;
    var stepV = window.step;
    nebPay.call(dappAddress, "0", "set", JSON.stringify([{
      username: usernameV, 
      active: activeV, 
      step: stepV
    }]), { 
      listener: function(res) {
        if (res.txhash) {
          layer.msg('信息存入需要一分钟，之后可刷新网页，查看排行榜');
          layer.closeAll();
        }
      }
    })
  });
})